package outils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.mortennobel.imagescaling.ResampleOp;

public class Outils {
		
	
	public static InputStream  redimensionImage(InputStream fileStream) throws IOException
	{
		BufferedImage imageBuf = ImageIO.read(fileStream);
		ResampleOp resampleOp = new ResampleOp(150, 225);
		BufferedImage resizedImageBuf = resampleOp.filter(imageBuf, null);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write(resizedImageBuf, "jpg", os);
		fileStream = new ByteArrayInputStream(os.toByteArray());
		return fileStream;
	}
	
	public static HttpSession getSession() {
        return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
      }
       
      public static HttpServletRequest getRequest() {
       return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
      }
 
      public static String getUserName()
      {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        return  session.getAttribute("username").toString();
      }
       
      public static String getUserId()
      {
        HttpSession session = getSession();
        if ( session != null )
            return (String) session.getAttribute("id");
        else
            return null;
      }
	
	
      public static int random()
      {
       return (int)( Math.random()*( 10000 - 1 + 1 ) ) + 1;
      }
	
	
	
	
	
	public static String getCryptedPassword(String notCryptedPassword) {
        MessageDigest md=null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
           // Logger.getLogger(AuthenticationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (md == null)
            return notCryptedPassword;
 
        md.update(notCryptedPassword.getBytes());
 
        byte input[] = md.digest();
 
        // Convert the byte variable to hexadecimal format
        StringBuilder hexaString = new StringBuilder();
    	for (int i=0;i<input.length;i++) {
    		String hexaChar=Integer.toHexString(0xff & input[i]);
   	     	if(hexaChar.length()==1) hexaString.append('0');
   	     	hexaString.append(hexaChar);
    	}
        return hexaString.toString();
    }
	
	
	
	
}
